package com.qf.fmw.Servlet;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取前端发送的请求数据 --  图片的相对路径
        String imgUrl = req.getParameter("imgUrl");
        //2.获取路径中的文件名
        String fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
        //3.设置响应头
        resp.setHeader("Content-disposition","attachment;fileName="+fileName);
        //4.创建输入流对象
        String realPath = getServletContext().getRealPath(imgUrl);
        FileInputStream fis = new FileInputStream(realPath);
        //5.获取输出流对象
        ServletOutputStream os = resp.getOutputStream();
        //6.实现拷贝
        IOUtils.copy(fis,os);
        //7.关闭资源
        fis.close();
        os.close();
    }
}
